package cn.gjxblog.controller;

import cn.gjxblog.api.UserServiceFegin;
import cn.gjxblog.common.model.HttpResult;
import cn.gjxblog.model.dto.CommentDTO;
import cn.gjxblog.model.entity.Comment;
import cn.gjxblog.model.entity.User;
import cn.gjxblog.model.vo.CommentVO;
import cn.gjxblog.service.CommentService;
import com.google.common.base.Objects;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/9 17:22
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserServiceFegin userServiceFegin;

    @PostMapping("/addComment")
    public HttpResult addComment(@RequestBody CommentDTO commentDTO){
        Integer type = commentDTO.getType();
        if(Objects.equal(1,type)){
            commentService.addHouseComment(commentDTO.getHouseId(),commentDTO.getContent(),commentDTO.getUserId());
        }else{
            commentService.addBlogComment(commentDTO.getBlogId(),commentDTO.getContent(),commentDTO.getUserId());
        }
        return HttpResult.success();
    }

    @PostMapping("/queryComment")
    public HttpResult<List<CommentVO>> queryComment(@RequestBody CommentDTO commentDTO){
        Integer type = commentDTO.getType();
        List<Comment> list = null;
        if(Objects.equal(1,type)){
            list = commentService.queryHouseComments(commentDTO.getHouseId(),commentDTO.getSize());

        }else{
            list = commentService.queryBlogComments(commentDTO.getBlogId(),commentDTO.getSize());
        }
        List<CommentVO> newlist = list.stream().map(comment -> toCommentVO(comment)).collect(Collectors.toList());
        return HttpResult.success(newlist);
    }

    private CommentVO toCommentVO(Comment comment) {
        CommentVO commentVO = new CommentVO();
        BeanUtils.copyProperties(comment, commentVO);
        HttpResult<User> result = userServiceFegin.getUserById(commentVO.getUserId());
        User user = result.getResult();
        if(user != null) {
            commentVO.setAvatar(user.getAvatar());
            commentVO.setUserName(user.getName());
        }
        return commentVO;
    }

}
